<?php
/**
 * 媒资管理上传
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 10:02
 */

namespace app\api\controller\homepage;

use app\api\controller\common\ApiBase;
use app\api\model\BaseCategory;
use app\api\model\MediaCates;
use app\api\model\MediaFiles;
use app\api\service\Uploader;
use think\Controller;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Loader;

class Media extends ApiBase
{

    protected $admin;
    protected $model = null;

    protected $file_model = null;

    public function _initialize()
    {
        $this->admin = session('admin');
        $this->model = new \app\api\model\Media();
        $this->file_model = new MediaFiles();
    }


    // getSeachertypes
    public function getSeachertypes()
    {

        $parent = db('jq_base_cate')->where([
            'is_delete' => 0,
            'status'    => 1,
            'parent_id' => 0
        ])->order('sort desc')->select();
        $list = db('jq_base_cate')->where([
            'is_delete' => 0,
            'status'    => 1,
            'parent_id' => array(
                'gt',
                0
            )
        ])->select();
        foreach ($parent as &$v) {
            $v['children'] = [];
            foreach ($list as &$vv) {
                if ($vv['parent_id'] == $v['id']) {
                    $v['children'][] = $vv;
                }
            }
        }


        return json([
            'code' => 1,
            'msg'  => 'success',
            'data' => $parent
        ]);

    }

    /**
     * 素材列表
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-12 23:19
     */
    public function list()
    {
        $data = $this->request->param();
        $this->model = new \app\api\model\Media();

        $list = $this->model->getList();

        $this->success('获取成功', '', $list);
    }


    public function detail()
    {

        $media_id = $this->request->post('media_id', 0);

        $detail = $this->model->getMediaData($media_id);

        if (empty($detail)) {
            $this->error('资源不存在');
        }

        $file_list = (new MediaFiles())->getList($media_id, 1);

        $this->success('获取成功', '', [
            'detail'    => $detail,
            'file_list' => $file_list
        ]);

    }

    /**
     *  批量下载资源
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-14 23:15
     */
    function download_media()
    {
        $media_id = $this->request->post('media_id', 0);

        $detail = $this->model->get($media_id);

        if (empty($detail)) {
            $this->error('资源不存在');
        }

        if ($detail['type'] != '0') {
            $this->error('只允许图片资源批量下载');
        }

        $map = [
            'media_id'   => $media_id,
            'is_deleted' => '0',
            'status'     => '1',
        ];
        $list = $this->file_model->where($map)->select();

        $root_path = dirname(APP_PATH) . '/public';
        $zip_name = '/zip/' . md5(microtime()) . '.zip';
        if ($list) {
            $zip = new \ZipArchive();
            $result = $zip->open('public' . $zip_name, \ZipArchive::CREATE);
            if ($result === TRUE) {
                $zip->addEmptyDir($detail['title']);
                foreach ($list as $item) {
                    if ($item['file_path']) {
                        $ext = (new Uploader())->getFileExt($item['file_path']);
                        $result = $zip->addFile(real_path($item['file_path']), $detail['title'] . '/' . $item['title'] . '.' . $ext);
                    }
                }
                $zip->close();
            } else {
                $this->error('下载异常');
            }
        }

        $this->file_model->where($map)->setInc('download_num');
        // 更新类目下载数量
        $this->model->updateDownloadNum($media_id);
        $this->success('获取成功', '', [
            'download_url' => cdnurl($zip_name)
        ]);
    }

    function addFileToZip($path, $zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..'，不要对他们进行操作
                if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹，则递归
                    $this->addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                }
            }
        }
        @closedir($path);
    }

    /**
     * 下载单个文件
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-14 23:16
     */
    function download_file()
    {
        $media_file_id = $this->request->post('media_file_id', 0);

        $detail = $this->file_model->get($media_file_id);

        if (empty($detail)) {
            $this->error('素材不存在');
        }

        $detail->setInc('download_num');
        // 更新类目下载数量
        $this->model->updateDownloadNum($detail['media_id']);
        $this->success('获取成功', '', [
            'download_url' => cdnurl($detail['file_path'])
        ]);
    }

    /**
     * 删除|批量删除
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-12 23:13
     */
    public function del()
    {

        $ids = $this->request->post('ids', '');
        if (empty($ids)) {
            $this->error('参数缺少或为空');
        }
        $ids = $ids ?
            explode(',', $ids) : [];
        $map = [];
        $map['id'] = [
            'in',
            $ids
        ];
        $result = $this->model->where($map)
            ->update(['is_deleted' => '1']);

        if ($result === false) {
            $this->error('删除失败');
        }
        $this->file_model->where([
            'media_id' => [
                'in',
                $ids
            ]
        ])->update(['is_deleted' => '1']);
        $this->file_model->del_dev_file($ids);
        foreach ($ids as $item) {
            // 更新类目下载数量
            $this->model->updateDownloadNum($item);
        }
        $this->success('删除成功');
    }

}